package com.banzhi.shop.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Login.Login_data;
import com.banzhi.shop.entity.NewLogin.LoginModelImpl;
import com.banzhi.shop.model.CallBack.LoginModelCallBack;
import com.banzhi.shop.model.CallBack.SendCodeCallBack;

import com.banzhi.shop.model.Impl.SendCodeImpl;
import com.banzhi.shop.utils.ClickUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.ShareSDK;

import static com.banzhi.shop.MyApp.context;

/*
*
* 验证码登录
*
* */
public class YanzhengmaLoginActivity extends BaseActivity implements View.OnClickListener,SendCodeCallBack,LoginModelCallBack,Handler.Callback {

    private SendCodeImpl mSendCodeModel;
    private ImageView mIvBack;
    private EditText mEtPhone;
    private EditText mEtCode;
    private TextView mTvSendCode;
    private Button mBtnLogin;
    private TextView mTvPassword;
    private LoginModelImpl mLoginModel;

    private static final int MSG_AUTH_CANCEL = 1;
    private static final int MSG_AUTH_ERROR = 2;
    private static final int MSG_AUTH_COMPLETE = 3;
    private Timer timer;
    private int number = 60;
    private Handler handler;
    private String mPhone;
    private String mCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_yanzhengma_login );
        Translucent.setTranslucent( this );
        mLoginModel = new LoginModelImpl();

        mSendCodeModel = new SendCodeImpl();
        ShareSDK.initSDK(this, "1dc05ab16fd6c");
        handler = new Handler( this );



        initView();
        setListeners();
    }

    //初始化界面
    private void initView() {
        mIvBack = (ImageView) findViewById( R.id.iv_back );
        mEtPhone = (EditText) findViewById( R.id.et_phone );
        mEtCode = (EditText) findViewById( R.id.et_code );
        mTvSendCode = (TextView) findViewById( R.id.tv_send_code );
        mBtnLogin = (Button) findViewById( R.id.btn_login );
        mTvPassword = (TextView) findViewById( R.id.tv_password_login );

    }

    private void setListeners() {
         mIvBack.setOnClickListener( this );
         mTvSendCode.setOnClickListener( this );
         mBtnLogin.setOnClickListener( this );
         mTvPassword.setOnClickListener( this );


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_send_code:
                mPhone = mEtPhone.getText().toString().trim();
                if (TextUtils.isEmpty( mPhone )) {
                    ToastUtils.makeToastShort( "请输入手机号码" );
                } else if (mPhone.length() < 11) {
                    ToastUtils.makeToastShort( "电话号码不符合规范" );
                } else {
                    LoadingDialogUtils.showProgress( this, "正在加载,请稍后~" );
                    mSendCodeModel.getData( mPhone, this );
                }

                break;
            case R.id.btn_login:
                //验证码登录获取数据
                if (ClickUtils.isFastClick()) {
                    mPhone = mEtPhone.getText().toString().trim();
                    mCode = mEtCode.getText().toString().trim();

                    if (TextUtils.isEmpty( mPhone )) {
                        ToastUtils.makeToastShort( "请输入手机号码" );
                    } else if (mPhone.length() < 11) {
                        ToastUtils.makeToastShort( "电话号码不符合规范" );
                    } else if (TextUtils.isEmpty( mCode )) {
                        ToastUtils.makeToastShort( "请输入验证码" );
                    } else {
                        LoadingDialogUtils.showProgress( this, "正在加载,请稍后~" );
                        mLoginModel.YZMlogin( mPhone, mCode, this );
                    }
                }

                break;
            case R.id.tv_password_login:
                Intent intent = new Intent( YanzhengmaLoginActivity.this, MimaLoginActivity.class );
                startActivity( intent );
                break;
        }

    }
    //发送验证码成功
    @Override
    public void sendCodeSuccess(Object object) {
        JSONObject object1 = (JSONObject) object;
        ToastUtils.makeToastShort(object1.optString("msg"));
        mTvSendCode.setClickable(false);
        if (timer == null) {
            timer = new Timer();
        } else {
            timer.cancel();
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                msg.what = 100;
                handler.sendMessage(msg);
            }
        }, 0, 998);

    }
    //发送验证码失败
    @Override
    public void sendCodeError(Object object) {
        JSONObject object1 = (JSONObject) object;
        ToastUtils.makeToastShort(object1.optString("msg"));

    }

    @Override
    public void onloginSuccess(Object object) {
        Login_data login = (Login_data) object;
        ToastUtils.makeToastShort("登录成功");

        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("token", login.getToken());
        editor.putString("id", login.getId());
        editor.putString("nickname", login.getNickname());
        editor.putString("openid_wx", login.getOpenid_wx());
        editor.putString("openid", login.getOpenid());
        editor.putString("mobile", login.getMobile());
        editor.putString("isagent",login.getIsagent()+"");
        editor.apply();

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();

        JPushInterface.setAlias(context,login.getMobile() ,
                new TagAliasCallback() {

                    @Override
                    public void gotResult(int responseCode,
                                          String alias, Set<String> tags) {
                        if (responseCode==0) {
                            System.out.println("jpush alias@@@@@别名设置成功");
                        }
                    }
                });


    }

    @Override
    public void onloginError(Object object) {
        LoadingDialogUtils.dismiss();
        JSONObject object1 = (JSONObject) object;
        ToastUtils.makeToastShort(object1.optString("msg"));

    }



    @Override
    public void onWXloginSuccess(Object object) {

    }

    @Override
    public void onWXloginError(Object object) {

    }

    @Override
    public void onBindingPhoneSuccess(Object object) {

    }

    //验证码登录成功
    @Override
    public void onYZMloginSuccess(Object object) {
        Login_data login = (Login_data) object;
        ToastUtils.makeToastShort("登录成功");

        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("token", login.getToken());
        editor.putString("id", login.getId());
        editor.putString("nickname", login.getNickname());
        editor.putString("openid_wx", login.getOpenid_wx());
        editor.putString("openid", login.getOpenid());
        editor.putString("mobile", login.getMobile());
        editor.apply();

        Intent intent = new Intent(YanzhengmaLoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
        //设置别名
        JPushInterface.setAlias(context,login.getMobile() ,
                new TagAliasCallback() {

                    @Override
                    public void gotResult(int responseCode,
                                          String alias, Set<String> tags) {
                        if (responseCode==0) {
                            System.out.println("jpush alias@别名设置成功");
                        }
                    }
                });
    }

    /*
    * 验证码登录失败
    *
    * */
    @Override
    public void onYZMloginError(Object object) {

        JSONObject object1 = (JSONObject) object;
        ToastUtils.makeToastShort( object1.optString( "msg" ) );

    }

    @Override
    public void onBindingLoginSuccess(Object object) {
    }

    @Override
    public void onBindingLoginError(Object object) {

    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 100:
                number--;
                mTvSendCode.setText(number + "");
                if (number < 0) {
                    mTvSendCode.setClickable(true);
                    mTvSendCode.setText("发送验证码");
                    number = 60;
                    timer.cancel();
                }

                break;
            case MSG_AUTH_CANCEL: // 取消
                ToastUtils.makeToastShort("登录取消");
                break;
            case MSG_AUTH_ERROR:
                // 失败
                Throwable t = (Throwable) msg.obj;
                String text = "登录失败: " + t.getMessage();
                ToastUtils.makeToastShort(text);
                t.printStackTrace();
                break;
            case MSG_AUTH_COMPLETE:
                // 成功
                HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
                try {


                    String openid = map.get("openid").toString();
                    mLoginModel.WXlogin(openid, this);

                } catch (Exception e) {
                    ToastUtils.makeToastShort("数据异常");
                }

                break;
        }
        return false;
    }


}

